package result

import (
	"github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
	"net/http"
	"shop/utils/convertutil"
)

type Result struct {
	// HttpCode    int         `json:"-"`
	// ContentType string      `json:"-"`
	Code int         `json:"code"`
	Msg  string      `json:"msg,omitempty"`
	Data interface{} `json:"data,omitempty"`
}

func (r *Result) SetCode(code int) *Result {
	r.Code = code
	return r
}

func (r *Result) SetMsg(msg string) *Result {
	r.Msg = msg
	return r
}

func (r *Result) SetData(data interface{}) *Result {
	r.Data = data
	return r
}

func Ok(data interface{}) *Result {
	return &Result{
		Code: ErrCodeOk,
		Msg:  "ok",
		Data: data,
	}
}

func Fail(msg string) *Result {
	return &Result{
		Code: ErrCodeFail,
		Msg:  msg,
		Data: nil,
	}
}

func RenderFail(c *gin.Context, msg string) {
	RenderResult(c, Fail(msg))
}

func RenderResult(c *gin.Context, res *Result) {
	if c.Request.Method == "GET" {
		seelog.Debugf("[%s] %s result.Msg=%s", c.Request.Method, c.FullPath(), res.Msg)
	} else {
		seelog.Debugf("[%s] %s接口返回结果：%v", c.Request.Method, c.FullPath(), convertutil.ToJsonString(res))
	}
	c.JSON(http.StatusOK, res)
}
